import base64
import csv
import json
import time
from urllib.parse import urlparse, parse_qs

import requests
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15

id = 155


# Function to perform RSA signing
def rsa_sign(raw, private_key):
    key = RSA.import_key(private_key)
    h = SHA256.new(raw.encode())
    signature = pkcs1_15.new(key).sign(h)
    return base64.b64encode(signature).decode()


# Function to perform RSA signing
def rsa_sign_sha256(data, private_key):
    key = RSA.import_key(private_key)
    hashed_data = SHA256.new(data.encode())
    signer = pkcs1_15.new(key)
    signature = signer.sign(hashed_data)
    return base64.b64encode(signature).decode()


# Your RSA private key
private_key = """
-----BEGIN PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJwHprdyHnyvW8GNuZeS6qnKgEnxKBd/Ag4V6fwHEeH5lnVmJ22poqjCMSsWSAz7l0rrXGIi/D9q2NytwUGzInpr5Ausysr0+0RDIeqYMTkntRq9KlfITDw8hOOq/RlX5Inwiix47wZ/eE2CsE8BzUjFxUWghbiIBX4C6t/b5hD1AgMBAAECgYBhLdrGUstuOQHbEVxQbW6+haNVal/gEnjDMR7km7qllgAB6rgP8yGeHiTlgyEpBOH8BY8qiEO3c+LRv16oftuvjuB424PS0SHQ4ShV/lhsafkRtbazfi5rcmL3pDj84mxsrlxX3url5H0ybxkpyFxxFT8JZpFT3metrqeac/ziGQJBAMk4Jof7dQebDFTC+dp6k9tc05oiphF9cKxisemkEg3dftzCFBswrf2a1XbHfASP8hZgIVz2Lw7rSQSR9ila698CQQDGgg07nBS1Kh5Mdudd51jn6ZIxMGccyXEBrLMIlAnjrVAS9boYD0Vut4gZr0tSZVsXAOcRFMVriH0hCNdC1d2rAkBZMItbsOjRwzb3BylqXvTUwdOFOaB0li5wKpsDndbm0Gvf/CKfXrdwdsXxjUB6YTeEFX4UT4bSTRYjcXM0J3nvAkBLau+iHRuU9MqMHISsnY+elJPxUkVqn3Hqw/VFJhFXyenpOiiYqXykot/3eizwwgdIhxRC3hRfVXzMxzIZd21/AkBjcFiC9Vv3NIVjqDnOrrqYQDZ4WXeMkKwWujvmbDxGwdx06FM2BemNoRWNPajp2lfKPCvR0MjD4TiKvfQ1Sap1
-----END PRIVATE KEY-----
""".strip()

timestamp = int(time.time() * 1000)

raw_message = f"id={id}&page=1&page_size=10000&timestamp={timestamp}"

print("request path:", raw_message)

signature_b64 = rsa_sign_sha256(raw_message, private_key)

print("Signature (Base64):", signature_b64)

url = f"http://merchant.cardplayer6.com/api/merchant/v1/product/template/cardList/list/select?client=merchant&{raw_message}"

# 解析URL
parsed_url = urlparse(url)

# 解析查询字符串参数
query_params = parse_qs(parsed_url.query)

# 转换查询参数为单值（而不是列表），适用于查询参数不是多值的情况
query_params = {k: v[0] for k, v in query_params.items()}

# 将参数转换为JSON对象
payload = json.dumps(query_params, indent=4)

# 打印结果
print(payload)

headers = {
    'DNT': '1',
    'Pragma': 'no-cache',
    'Proxy-Connection': 'keep-alive',
    'X-Token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJkb3VjbG91ZCIsImlhdCI6MTcwNDY5NDUzMSwiZXhwIjoxNzA1Mjk5MzMxLCJkYXRhIjp7InVzZXJuYW1lIjoiMTUzNjQ5MDk4MTUiLCJ1c2VyX2lkIjo5OX19.zFF1EcBy-gHQMJoU4C6uCiG9Pw6Pd7RYVfAuhR8c19Y',
    'client': 'merchant',
    'region-code': '',
    'sign': f"{signature_b64}",
    'timestamp': f"{timestamp}",
    'Cookie': 'b-user-id=68b4d544-7852-4a46-b1bf-1258632e0d14; SL_G_WPT_TO=zh; SL_GWPT_Show_Hide_tmp=1; SL_wptGlobTipTmp=1; card_merchant_token=U2FsdGVkX1+4v4/TtQpoT1SGUQvN7f6M8unMkVYhsfOmR7jhBsgD0/6CKGdRd7bWI5XAfCQ4nDT3p8BnjEUYVBsx7fBiOhihgH4d+Vwo+Ldtniq35hFpGl/FVHh1uxUZ+dkE3ollWyIMV5tgOmRkEBhfXysRX+pckV4kw6mNTtBvfZ7BMURp26Jx7npD7FcCbsol62kEk/yjAnpRlfzdp7iOo7/eQ4qrl/uodrTHTOt9QIfCHVlwKNCIBz4Cx602RlOaFs/feQjZw4qA4TWHjMcBzUBIZki8W1SDLZzcYnfr8dV86qsTWfnnD76F8c30',
    'Content-Type': 'application/json;charset=utf-8'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)

# json_file = "body.json"
csv_file = f"{id}-kalai.csv"

# 读取 JSON 文件
# with open(json_file, "r", encoding='utf-8') as file:
#     json_str = file.read()

# 解析 JSON 字符串为字典对象
# data = json.loads(json_str)

data = json.loads(response.text)
list_data = data["data"]["list"]

# 写入 CSV 文件
with open(csv_file, mode="w", newline="") as file:
    fieldnames = list_data[0].keys()
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(list_data)

print("CSV file created successfully.")
